from common.api import http_result
from user_module.rpc import user_pb2_grpc
from user_module.models import Role, MenuInfo
import json


class RoleHandler(user_pb2_grpc.RoleServicer):

    def do_query(self, param, session):
        roles = Role.select().offset(0).limit(10)
        result = []
        for r in roles:
            tmp = {
                'id': r.id,
                'name': r.name,
                'menus': [],
            }
            if r.menus == '***':
                tmp['menus'] = ['***']
            else:
                menus = json.loads(r.menus)
                ms = MenuInfo.select(MenuInfo.menu).where(MenuInfo.id.in_(menus))
                for m in ms:
                    tmp['menus'].append(m.menu)

            result.append(tmp)
        return self.resp(1, http_result.RESULT_SUCCESS, result)

    def do_update(self, param, session):
        rid = param.get('id')
        if not rid:
            role = Role()
        else:
            role = Role.get_by_id(rid)
        role.name = param.get('name')
        role.menus = param.get('menus')
        role.save()

        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_delete(self, param, session):
        rid = param.get('id')
        if not rid:
            return self.need_param('id')
        Role.delete().where(Role.id == rid).execute()
        return self.resp(1, http_result.RESULT_SUCCESS)
